import { applicationWindowEval } from "../../services";
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { OsType, type } from "@tauri-apps/plugin-os";

import { Webview } from '@tauri-apps/api/webview';
import { Window, LogicalSize, LogicalPosition, getCurrentWindow } from '@tauri-apps/api/window';
import { InstalledApplication, ProjectApplicationType } from "@/services/local";

export const openApplication = async (item: InstalledApplication) => {

    console.log(item);
    //
    try {
        let windowIdentifier = `browser`;
        let win = await Window.getByLabel(windowIdentifier);

        let url: string | null = null;
        if (item.application_type === ProjectApplicationType.Agent) {
            url = `/#/application/true/${item.identifier}`
        } else if (item.application_type === ProjectApplicationType.CustomH5) {
            let indexPage = '/index.html'
            if (item.main && item.main.length > 1) {
                indexPage = item.main;
            }
            //查询 windowIdentifier是否存在
            let pathIdentifier = `${item.project_identifier || ''}_${item.identifier}`;
            url = `rrg01://${pathIdentifier}.localhost${indexPage}`;
            if (type() === 'windows') {
                url = `http://rrg01.${pathIdentifier}.localhost${indexPage}`;
            }
        } else {
            let indexPage = '/index.html'
            if (item.main && item.main.length > 1) {
                indexPage = item.main;
            }
            //查询 windowIdentifier是否存在
            let pathIdentifier = `${item.project_identifier || ''}_${item.identifier}`;
            url = `rrg01://${pathIdentifier}.localhost${indexPage}`;
            if (type() === 'windows') {
                url = `http://rrg01.${pathIdentifier}.localhost${indexPage}`;
            }
        }
        console.log(url);

        if (!win) {
            win = new WebviewWindow(windowIdentifier, {
                url: url,
                title: item.name,
                width: 1200,
                height: 800,
            });
            win.once('tauri://created', async function () {
                // window successfully created
                await applicationWindowEval(windowIdentifier, `window.location.replace('${url}')`);
                await win.show();
            });
            win.once('tauri://error', function (e) {
                console.log(e);
            });
        } else {
            //
            await applicationWindowEval(windowIdentifier, `window.location.replace('${url}')`);
            await win.show();
        }
    } catch (err) {
        console.log(err);
    }
}